#pragma once
#include <iostream>
#include <string>
#include <cstring>
#include <cstdio>
#include <set>
#include "Log.hpp"
#include "InetAddr.hpp"

class Command
{
public:
    Command(){}

    std::string Execute(const std::string &cmdstr)
    {
        FILE *fp = popen(cmdstr.c_str(), "r");
        if(fp)
        {
            char line[1024];
            std::string result;
            while(fgets(line, sizeof(line), fp))
            {
                result += line;
            }
            return result.empty() ? "success" : result;
        }
        return "execute error";
    }

    void HandlerCommand(int sockfd, InetAddr addr)
    {
        while(true)
        {
            char buffer[1024];
            ssize_t n = ::recv(sockfd, buffer, sizeof(buffer) - 1, 0);
            if (n > 0)
            {
                buffer[n] = 0;
                std::string result = Execute(buffer);
                ::send(sockfd, result.c_str(), result.size(), 0);
            }
            else if (n == 0)
            {
                LOG(INFO, "client %s quit\n", addr.addrStr().c_str());
                break;
            }
            else
            {
                LOG(ERROR, "read error: %s\n", addr.addrStr().c_str());
                break;
            }
        }
    }
    ~Command(){}
};